# -*- coding: utf-8 -*-
# @Time    : 2016/9/22
import re
from sympy import expand, simplify
from mathsolver.functions.base.base import BaseFunction, new_latex
from mathsolver.functions.base.objects import BasePoly


class HanShuPingJunBianHuaLu(BaseFunction):
    """函数的平均变化率"""

    @staticmethod
    def delta_process(sympy_expression):
        p = re.compile(r"\\Delta\{\\left \((.*?) \\right \)\}")
        return p.sub(r"\Delta \1", new_latex(sympy_expression))

    def solver(self, *args):
        fun, p1, p2 = args[0], args[1].sympify(evaluate=True), args[2].sympify(evaluate=True)
        # 从输入推导出 Delta(x) 和 Delta(y)
        d_x, d_y = expand(p2[0] - p1[0]), expand(p2[1] - p1[1])
        # 计算 Delta(y)
        d_y_cal = expand(fun.expression.subs(fun.var, p2[0]) - fun.expression.subs(fun.var, p1[0]))
        result = simplify(d_y_cal / d_x)
        self.steps.append(["因为 {0} = {1}({2}) - {1}({3}) = {4}"
                          .format(self.delta_process(d_y),
                                  fun.name,
                                  self.delta_process(p2[0]),
                                  self.delta_process(p1[0]),
                                  self.delta_process(d_y_cal)),
                           "所以 \frac {{{0}}}{{{1}}} = \frac {{{2}}}{{{1}}} = {3}"
                          .format(self.delta_process(d_y),
                                  self.delta_process(d_x),
                                  self.delta_process(d_y_cal),
                                  self.delta_process(result))])
        self.output.append(BasePoly(result))
        self.label.add("函数的平均变化率")
        return self


if __name__ == "__main__":
    pass
